package com.cmic.rcs.emoji.util;

import com.cmic.rcs.emoji.common.UserContext;
import com.cmic.rcs.emoji.entity.dto.UserDto;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * 通讯录接口工具类
 */
@Component
@Slf4j
public class AddressBookApiUtil {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${address-book.host}")
    private String host;

    @Value("${address-book.appKey}")
    private String appKey;

    @Value("${address-book.appSecret}")
    private String appSecret;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 批量获取企业信息
     * @param orgIds 企业ID列表
     * @return 企业信息映射，key为orgId，value为orgName
     */
    public Map<Long, String> batchGetEnterpriseNames(List<Long> orgIds) {
        if (orgIds == null || orgIds.isEmpty()) {
            return Collections.emptyMap();
        }

        Map<Long, String> resultMap = new HashMap<>();
        try {
            // 构建请求URL
            String url = host + "/v1/origin/addrBookExternal/api/department/getUserOrgInfos";

            // 构建请求参数
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("orgIds", orgIds);

            // 获取当前用户信息
            UserDto userDto = UserContext.getUserDto();
            String operator = userDto != null ? userDto.getUsername() : "system";
            String clientId = "emoji-system";

            // 转换请求体为JSON字符串
            String strJson = objectMapper.writeValueAsString(requestBody);

            // 设置请求头
            HttpHeaders headers = setHeader(strJson, operator, clientId);

            // 创建请求实体
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

            log.info("批量获取企业信息请求，orgIds: {}, url: {}", orgIds, url);

            // 使用ParameterizedTypeReference避免类型擦除问题
            ParameterizedTypeReference<Map<String, Object>> responseType = new ParameterizedTypeReference<Map<String, Object>>() {};

            // 发送请求
            ResponseEntity<Map<String, Object>> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    requestEntity,
                    responseType
            );

            // 处理响应
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                Map<String, Object> responseBody = response.getBody();
                // 安全的类型转换
                Integer code = responseBody.get("code") instanceof Integer ? (Integer) responseBody.get("code") : null;
                if (code != null && code == 0) {
                    // 安全的类型转换
                    if (responseBody.get("data") instanceof Map) {
                        Map<String, Object> data = (Map<String, Object>) responseBody.get("data");
                        // 安全的类型转换
                        if (data.get("orgDetails") instanceof List) {
                            List<?> orgDetailsList = (List<?>) data.get("orgDetails");
                            for (Object item : orgDetailsList) {
                                if (item instanceof Map) {
                                    Map<?, ?> orgDetail = (Map<?, ?>) item;
                                    // 安全的类型转换
                                    if (orgDetail.get("orgId") instanceof Number && orgDetail.get("orgName") instanceof String) {
                                        Long orgId = ((Number) orgDetail.get("orgId")).longValue();
                                        String orgName = (String) orgDetail.get("orgName");
                                        resultMap.put(orgId, orgName);
                                    }
                                }
                            }
                        }
                    }
                } else {
                    log.error("批量获取企业信息失败，code: {}, message: {}", code, responseBody.get("msg"));
                }
            } else {
                log.error("批量获取企业信息响应异常，status: {}", response.getStatusCodeValue());
            }
        } catch (Exception e) {
            log.error("批量获取企业信息异常", e);
        }

        return resultMap;
    }

    /**
     * 获取用户信息
     */

    /**
     * 根据手机号获取企业成员姓名
     * @param orgId 企业ID
     * @param mobile 手机号
     * @return 成员姓名，如果获取失败返回null
     */
    public String getMemberNameByPhone(Long orgId, String mobile) {
        try {
            // 构建请求URL
            String url = host + "/v1/origin/addrBookExternal/api/department/queryOrgUserInfo";

            // 构建请求参数
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("orgId", orgId);
            requestBody.put("mobile", mobile);

            // 获取当前用户信息
            UserDto userDto = UserContext.getUserDto();
            String operator = userDto != null ? userDto.getUsername() : "system";
            String clientId = "emoji-system";

            // 转换请求体为JSON字符串
            String strJson = objectMapper.writeValueAsString(requestBody);

            // 设置请求头
            HttpHeaders headers = setHeader(strJson, operator, clientId);

            // 创建请求实体
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

            log.info("查询企业成员信息，orgId: {}, mobile: {}, url: {}", orgId, mobile, url);

            // 使用ParameterizedTypeReference避免类型擦除问题
            ParameterizedTypeReference<Map<String, Object>> responseType = new ParameterizedTypeReference<Map<String, Object>>() {};

            // 发送请求
            ResponseEntity<Map<String, Object>> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    requestEntity,
                    responseType
            );

            // 处理响应
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                Map<String, Object> responseBody = response.getBody();
                // 安全的类型转换
                Integer code = responseBody.get("code") instanceof Integer ? (Integer) responseBody.get("code") : null;
                if (code != null && code == 0) {
                    // 安全的类型转换
                    if (responseBody.get("data") instanceof Map) {
                        Map<?, ?> data = (Map<?, ?>) responseBody.get("data");
                        // 安全的类型转换
                        String name = data.get("name") instanceof String ? (String) data.get("name") : null;
                        log.info("查询企业成员信息成功，orgId: {}, mobile: {}, name: {}", orgId, mobile, name);
                        return name;
                    }
                } else {
                    log.error("查询企业成员信息失败，code: {}, message: {}", code, responseBody.get("msg"));
                }
            } else {
                log.error("查询企业成员信息响应异常，status: {}", response.getStatusCodeValue());
            }
        } catch (Exception e) {
            log.error("查询企业成员信息异常", e);
        }

        return null;
    }

    /**
     * 检查手机号是否在指定企业中
     * @param orgId 企业ID
     * @param mobile 手机号
     * @return true表示手机号在企业中，false表示不在
     */
    public boolean checkMobileInEnterprise(Long orgId, String mobile) {
        try {
            // 构建请求URL
            String url = host + "/v1/origin/addrBookExternal/api/department/checkIsInOrg";

            // 构建请求参数
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("orgId", orgId);
            requestBody.put("mobile", mobile);

            // 获取当前用户信息
            UserDto userDto = UserContext.getUserDto();
            String operator = userDto != null ? userDto.getUsername() : "system";
            String clientId = "emoji-system";

            // 转换请求体为JSON字符串
            String strJson = objectMapper.writeValueAsString(requestBody);

            // 设置请求头
            HttpHeaders headers = setHeader(strJson, operator, clientId);

            // 创建请求实体
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

            log.info("检查手机号是否在企业中，orgId: {}, mobile: {}, url: {}", orgId, mobile, url);

            // 使用ParameterizedTypeReference避免类型擦除问题
            ParameterizedTypeReference<Map<String, Object>> responseType = new ParameterizedTypeReference<Map<String, Object>>() {};

            // 发送请求
            ResponseEntity<Map<String, Object>> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    requestEntity,
                    responseType
            );

            // 处理响应
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                Map<String, Object> responseBody = response.getBody();
                // 安全的类型转换
                Integer code = responseBody.get("code") instanceof Integer ? (Integer) responseBody.get("code") : null;
                if (code != null && code == 0) {
                    // 安全的类型转换
                    if (responseBody.get("data") instanceof Map) {
                        Map<?, ?> data = (Map<?, ?>) responseBody.get("data");
                        // 安全的类型转换
                        Boolean isInOrg = data.get("isInOrg") instanceof Boolean ? (Boolean) data.get("isInOrg") : false;
                        log.info("检查手机号是否在企业中通过，orgId: {}, mobile: {}, isInOrg: {}", orgId, mobile, isInOrg);
                        return isInOrg;
                    }
                } else {
                    log.error("检查手机号是否在企业中失败，code: {}, message: {}", code, responseBody.get("msg"));
                }
            } else {
                log.error("检查手机号是否在企业中响应异常，status: {}", response.getStatusCodeValue());
            }
        } catch (Exception e) {
            log.error("检查手机号是否在企业中异常", e);
        }

        return false;
    }

//      * 通过企业名称查询企业信息
//     * @param orgName 企业名称
//     * @return 企业信息列表
//     */
    public List<Map<String, Object>> queryEnterpriseByOrgName(String orgName) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        try {
            // 构建请求URL
            String url = host + "/v1/origin/addrBookExternal/api/enterprise/queryByOrgName";

            // 构建请求参数
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("orgName", orgName);

            // 获取当前用户信息
            UserDto userDto = UserContext.getUserDto();
            String operator = userDto != null ? userDto.getUsername() : "system";
            String clientId = "emoji-system";

            // 转换请求体为JSON字符串
            String strJson = objectMapper.writeValueAsString(requestBody);

            // 设置请求头
            HttpHeaders headers = setHeader(strJson, operator, clientId);

            // 创建请求实体
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

            log.info("通过企业名称查询企业信息请求，orgName: {}, url: {}", orgName, url);

            // 使用ParameterizedTypeReference避免类型擦除问题
            ParameterizedTypeReference<Map<String, Object>> responseType = new ParameterizedTypeReference<Map<String, Object>>() {};

            // 发送请求
            ResponseEntity<Map<String, Object>> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    requestEntity,
                    responseType
            );

            // 处理响应
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                Map<String, Object> responseBody = response.getBody();
                // 安全的类型转换
                Integer code = responseBody.get("code") instanceof Integer ? (Integer) responseBody.get("code") : null;
                if (code != null && code == 0) {
                    // 安全的类型转换
                    if (responseBody.get("data") instanceof List) {
                        List<?> dataList = (List<?>) responseBody.get("data");
                        for (Object item : dataList) {
                            if (item instanceof Map) {
                                @SuppressWarnings("unchecked")
                                Map<String, Object> enterpriseInfo = (Map<String, Object>) item;
                                resultList.add(enterpriseInfo);
                            }
                        }
                        log.info("通过企业名称查询企业信息成功，orgName: {}, resultSize: {}", orgName, resultList.size());
                    }
                } else {
                    log.error("通过企业名称查询企业信息失败，code: {}, message: {}", code, responseBody.get("msg"));
                }
            } else {
                log.error("通过企业名称查询企业信息响应异常，status: {}", response.getStatusCodeValue());
            }
        } catch (Exception e) {
            log.error("通过企业名称查询企业信息异常", e);
        }

        return resultList;
    }



    /**
     * 设置请求头
     */
    private HttpHeaders setHeader(String body, String operator, String clientId) {
        try {
            String uuid = CommonUtils.getUuid();
            String signStr = "appKey=" + appKey + "body=" + body + "client_id=" + clientId + "uMobile=" + operator + "uuid=" + uuid + appSecret;
            String sign = DigestUtils.sha1Hex(signStr);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("client_id", clientId);
            headers.set("appKey", appKey);
            headers.set("uMobile", operator);
            headers.set("uuid", uuid);
            headers.set("sign", sign);

            log.debug("设置第三方接口请求头: {}", objectMapper.writeValueAsString(headers));
            return headers;
        } catch (Exception e) {
            log.error("生成签名失败", e);
            return new HttpHeaders();
        }
    }
}